package com.example.hzly.controller;

import com.example.hzly.common.Result;
import com.example.hzly.dto.RegisterRequest;
import com.example.hzly.entity.User;
import com.example.hzly.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost:9000", "http://localhost:5173", "http://localhost:3000", "http://127.0.0.1:9000"}, allowCredentials = "true")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        log.info("收到登录请求: {}", loginRequest);
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        
        if (username == null || password == null) {
            return Result.error("用户名和密码不能为空");
        }
        
        User user = userService.findByUsernameAndPassword(username, password);
        if (user == null) {
            return Result.error("用户名或密码错误");
        }
        
        // 构建返回的用户信息（不包含密码）
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("name", user.getName());
        userInfo.put("avatar", user.getAvatar());
        
        log.info("登录成功: {}", username);
        return Result.ok(userInfo);
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterRequest registerRequest) {
        log.info("收到注册请求: {}", registerRequest);
        String username = registerRequest.getUsername();
        String password = registerRequest.getPassword();
        
        if (username == null || password == null) {
            log.error("注册失败: 用户名或密码为空");
            return Result.error("用户名和密码不能为空");
        }
        
        try {
            // 检查用户名是否已存在
            User existingUser = userService.findByUsername(username);
            if (existingUser != null) {
                log.error("注册失败: 用户名已存在 - {}", username);
                return Result.error("用户名已存在");
            }
            
            // 创建新用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setName(username); // 默认使用用户名作为显示名称
            newUser.setAvatar("default-avatar.jpg");
            
            boolean success = userService.save(newUser);
            if (success) {
                log.info("注册成功: {}", username);
                return Result.ok("注册成功");
            } else {
                log.error("注册失败: 保存用户失败 - {}", username);
                return Result.error("注册失败");
            }
        } catch (Exception e) {
            log.error("注册异常: ", e);
            String errorMsg = "注册失败";
            if (e.getMessage().contains("Duplicate entry")) {
                errorMsg = "用户名已存在";
            } else if (e.getMessage().contains("TooManyResultsException")) {
                errorMsg = "数据库中存在重复的用户名，请联系管理员";
            }
            return Result.error(errorMsg);
        }
    }

    @PostMapping("/logout")
    public Result<String> logout() {
        log.info("用户退出登录");
        return Result.ok("退出成功");
    }

    @GetMapping("/test")
    public Result<String> test() {
        log.info("测试数据库连接");
        try {
            // 尝试查询用户表
            long count = userService.count();
            log.info("用户表记录数: {}", count);
            return Result.ok("数据库连接正常，用户表记录数: " + count);
        } catch (Exception e) {
            log.error("数据库连接测试失败: ", e);
            return Result.error("数据库连接失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/check-duplicates")
    public Result<String> checkDuplicates() {
        log.info("检查重复用户名");
        try {
            // 这里可以添加检查重复用户名的逻辑
            // 暂时返回简单的检查结果
            long count = userService.count();
            return Result.ok("用户表总记录数: " + count + "，建议执行数据库清理脚本");
        } catch (Exception e) {
            log.error("检查重复用户名失败: ", e);
            return Result.error("检查失败: " + e.getMessage());
        }
    }

    /**
     * 用户信息修改
     */
    @PostMapping("/update")
    public Result<String> updateUser(@RequestBody Map<String, String> req) {
        Long id = req.get("id") == null ? null : Long.valueOf(req.get("id"));
        String name = req.get("name");
        String username = req.get("username");
        String password = req.get("password");
        if (id == null) return Result.error("参数错误");
        User user = userService.getById(id);
        if (user == null) return Result.error("用户不存在");
        if (name != null && !name.isEmpty()) user.setName(name);
        if (username != null && !username.isEmpty()) user.setUsername(username);
        if (password != null && !password.isEmpty()) user.setPassword(password);
        userService.updateById(user);
        return Result.ok("修改成功");
    }

    /**
     * 注销账号
     */
    @PostMapping("/delete")
    public Result<String> deleteUser(@RequestBody Map<String, String> req) {
        Long id = req.get("id") == null ? null : Long.valueOf(req.get("id"));
        if (id == null) return Result.error("参数错误");
        boolean ok = userService.removeById(id);
        if (ok) return Result.ok("账号已注销");
        return Result.error("注销失败");
    }
} 